package codegen

import (
	"gitee.com/hxchjm/goge/codegen/utils"
	"github.com/siddontang/go/config"
	"path/filepath"
	"strings"
)

const dockerfileTemplate = `#根目录下执行：docker build -t {{.serviceName}}  -f {{.serviceDir}}/Dockerfile .
FROM golang:1.19 AS builder

WORKDIR /build
ENV GOPROXY https://goproxy.cn
COPY go.mod .
COPY go.sum .
RUN go mod download

COPY . .
RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o {{.serviceName}} /build/{{.serviceDir}}/cmd


FROM ubuntu
ENV TZ Asia/Shanghai

WORKDIR /app
COPY --from=builder /build/{{.serviceName}} /app/
COPY --from=builder /build/{{.serviceDir}}/configs /app/configs

CMD ["/app/{{.serviceName}}","-log.dir","/data/logs/{{.serviceName}}","-conf","/app/configs"]

###################################################
#根目录下执行：docker build -t {{.serviceName}}  -f Dockerfile .
#FROM golang:1.17-alpine AS builder

#WORKDIR /build
#RUN adduser -u 10001 -D app-runner

#ENV GOPROXY https://goproxy.cn
#COPY go.mod .
#COPY go.sum .
#RUN go mod download

#COPY . .
#RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o {{.serviceName}} ./cmd

#FROM alpine AS final
#WORKDIR /app
#COPY --from=builder /build/{{.serviceName}} /app/
#COPY --from=builder /build/configs /app/configs
#COPY --from=builder /etc/passwd /etc/passwd
#COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

#USER app-runner

#CMD ["/app/{{.serviceName}}","-log.dir","/data/logs/{{.serviceName}}","-conf","/app/configs"]
`

func genDockerfile(dir, rootPkg string, cfg *config.Config, filename string) error {
	svrDir := filepath.ToSlash(dir)
	dirs := strings.SplitN(rootPkg, "/", 2)
	if len(dirs) == 2 {
		svrDir = dirs[1]
	}
	svrName := filepath.Base(rootPkg)
	return utils.GenFile(utils.FileGenConfig{
		Dir:          dir,
		Subdir:       "",
		Filename:     filename,
		TemplateName: "mainTemplate",
		//Category:        category,
		//TemplateFile:    mainTemplateFile,
		BuiltinTemplate: dockerfileTemplate,
		Data: map[string]string{
			//"importPackages": genAppImports(rootPkg),
			"serviceDir":  svrDir,
			"serviceName": svrName,
		},
	})
}
